package com.yxy.springcloud.framework.unionauth.controller;

import com.yxy.springcloud.framework.common.base.BusinessException;
import com.yxy.springcloud.framework.common.base.RestResponse;
import com.yxy.springcloud.framework.common.redis.RedisUtils;
import com.yxy.springcloud.framework.unionauth.DTO.AppRouterDto;
import com.yxy.springcloud.framework.unionauth.dao.AppMapper;
import com.yxy.springcloud.framework.unionauth.model.App;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yuxiaoyang
 * 将某个app的路由信息保存到redis中
 */
@RestController
@RequestMapping("/router")
public class RouterController {
  @Resource
  private RedisUtils redisUtils;

  @Resource
  private AppMapper appMapper;

  @PostMapping("/save")
  public RestResponse saveRouter(@RequestBody AppRouterDto inputDto) throws BusinessException{
    String appName = inputDto.getAppName();
    Long appId;

    App queryObj = new App();
    queryObj.setName(appName);

    List<App> dbList = appMapper.select(queryObj);
    if (dbList.size() == 0) {//不存在app, 则不允许注册
      throw new BusinessException(503, "app不存在,无法注册路由, 请先在union auth上进行app创建");
    } else {
      appId = dbList.get(0).getId();
    }
    // 将app路由写入redis
    redisUtils.set("auth#route#" + appName, inputDto.getRouter());
    RestResponse restResponse = new RestResponse(200, "success");
    return restResponse;
  }
}
